package com.example.helloworld;

import java.io.*;
import java.net.*;

public class GreetingServer extends Thread {
    private ServerSocket serverSocket;
    public GreetingServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
        serverSocket.setSoTimeout(10000);
    }
    public void run() {
        while (true) {
            try {
                System.out.println("等待远程连接，端口号为:" + serverSocket.getLocalPort() + "...");
                Socket socket = serverSocket.accept();
                System.out.println("远程主机地址为:" + socket.getRemoteSocketAddress());
                DataInputStream in = new DataInputStream(socket.getInputStream());
                System.out.println(in.readUTF());
                DataOutputStream out = new DataOutputStream(socket.getOutputStream());
                out.writeUTF("Hello, client!");
                socket.close();

            } catch (SocketTimeoutException s) {
                System.out.println("等待超时，继续等待...");
            } catch (IOException e) {
                e.printStackTrace();
                break;
            }
        }
    }

    public static void main(String[] args) {
        int port = Integer.parseInt("8080");
        try {
            Thread t = new GreetingServer(port);
            t.run();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
